﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using AgencyEntityLib.BaseEntity;


using OutdoorLib.BaseEntity;
using OutdoorLib.BaseEntity.Face;
using OutdoorLib.BaseEntity.Contract;
using OutdoorLib.BaseEntity.Constraction;
using Grishko.DataTier.SqlLibrary;
using Grishko.DataTier;
using OutdoorLib.BaseEntity.WS;
using OutdoorLib.BaseEntity.Agency;
using System.Text;
using System.IO;
using Grishko.UI;

/// <summary>
/// Summary description for ws_Hints
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
 [System.Web.Script.Services.ScriptService]
public class ws_Hints : System.Web.Services.WebService
{

    public ws_Hints()
    {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }


    /// <summary>
    /// Списки параметров по задачам
    /// </summary>
    /// <param name="prefixText"></param>
    /// <param name="count"></param>
    /// <returns></returns>
    [WebMethod]

    public string[] GetTaskListParams(string prefixText, int count)
    {
        TaskList.sqlLoadStatment Statment = new TaskList.sqlLoadStatment();
        List<string> source = ws_Hints.GetStringSource(Statment, "TaskListParams");
        return GetHints(source, prefixText, count);
        
    }

    /// <summary>
    /// Списки параметров по клиентам
    /// </summary>
    /// <param name="prefixText"></param>
    /// <param name="count"></param>
    /// <returns></returns>
    [WebMethod]
    public string[] GetClientListParams(string prefixText, int count)
    {
        ClientList.sqlLoadStatment Statment = new ClientList.sqlLoadStatment();
        List<string> source = ws_Hints.GetStringSource(Statment, "ClientListParams");
        return GetHints(source, prefixText, count);

    }

    /// <summary>
    /// Список параметров поиска контракта
    /// </summary>
    /// <param name="prefixText"></param>
    /// <param name="count"></param>
    /// <returns></returns>
    [WebMethod]
    public string[] GetCotractListParams(string prefixText, int count)
    {
        ContractList.sqlLoadStatment Statment = new ContractList.sqlLoadStatment();
        List<string> source = ws_Hints.GetStringSource(Statment, "CotractListParams");
        return GetHints(source, prefixText, count);

    }

    /// <summary>
    /// параметры по контактным лицам
    /// </summary>
    /// <param name="prefixText"></param>
    /// <param name="count"></param>
    /// <returns></returns>
    [WebMethod]
    public string[] GetContactFacesParams(string prefixText, int count)
    {
        ContactFaceList.sqlLoadStatment Statment = new ContactFaceList.sqlLoadStatment();
        List<string> source = ws_Hints.GetStringSource(Statment, "ContactFacesParams");
        return GetHints(source, prefixText, count);

    }


    /// <summary>
    /// Параетры по конструкции
    /// </summary>
    /// <param name="prefixText"></param>
    /// <param name="count"></param>
    /// <returns></returns>
    [WebMethod]
    public string[] GetConstractionsParams(string prefixText, int count)
    {
        //ConstractionList.sqlLoadStatment Statment = new ConstractionList.sqlLoadStatment();
        //List<string> source = ws_Hints.GetStringSource(Statment, "ConstractionsParams");
        //return GetHints(source, prefixText, count);
        return new string[] {""};
    }


    /// <summary>
    /// Параметры по поверхностям
    /// </summary>
    /// <param name="prefixText"></param>
    /// <param name="count"></param>
    /// <returns></returns>
    [WebMethod]
    public string[] GetSurfaceListParams(string prefixText, int count)
    {
        SideListWithContracts.SqlLoadStatment Statment = new SideListWithContracts.SqlLoadStatment();
        List<string> source = ws_Hints.GetStringSource(Statment, "SurfaceListParams");
        return GetHints(source, prefixText, count);
    }


    private string[] GetHints(List<string> source, string prefixText, int count)
    {

        if (prefixText.Length == 0)
            return source.ToArray<string>();
        int i = prefixText.LastIndexOf(" ");
        string FndStr = prefixText.Substring(i == -1 ? 0 : i).Trim().ToUpper();
        List<string> res = new List<string>();
        int j = 0;
        foreach (string item in source)
        {
            if (item.ToUpper().IndexOf(FndStr) > -1)
                res.Add(item);
            j++;

            if (j == count)
                return res.ToArray<string>();
        }
        return res.ToArray<string>();


    }

    public static List<string> GetStringSource (ListLoadStatment Statment,string KeyPref)
    {
        string key = HttpContext.Current.User.Identity.Name +   KeyPref;
        if (!CacheTools.IsCacheObject(key))
        {            
            List<string> res = Statment.GetHintFindStrings();
            CacheTools.SetCacheObject(key, res);
            return res;
        }
        return (List<string>) CacheTools.GetCacheObect(key);

        
    }

    /// <summary>
    /// Возможно ли вставить поверхность.
    /// Возвращает: -1 сервис не отработал - либо отработал с ошибкой ;  0- в даноом периоде нет пресечений - вставить можно либо порядковый номер в очереди    
    /// </summary>
    /// <param name="dtStart"></param>
    /// <param name="dtEnd"></param>
    /// <param name="Weight">Вес поверхности </param>
    /// <param name="ID">ContractSurfaceItem_ID </param>
    /// <param name="ID">SideSurfCount  поверхностей на стороне </param>
    /// <param name="ID">ContractPrice введенная цена</param>
    /// 
    /// <returns></returns>
    [WebMethod]
    public CallBackValue_SetSurface  Check_Q_Surface(string SideID, string dtStart, string dtEnd, 
                                        string ContractSurfaceItem_ID, int Weight, int SideSurfCount,
                                        int ContractPrice, string DayCount_ID, string Summa_ID)
    {

        CallBackValue_SetSurface res = new CallBackValue_SetSurface() { SurfNumber = -1, DaysCount_ID = DayCount_ID, Summa_ID = Summa_ID };
        DateTime _dtStart= Convert.ToDateTime(dtStart);
        DateTime _dtEnd= Convert.ToDateTime(dtEnd);

        // если dtStart> dtEnd - считаем что идет редактирование не проверяем очередь 
        if (_dtStart > _dtEnd)
                            return  res;

        ContractSurfaceItem i= new ContractSurfaceItem()
            {
                ID = ContractSurfaceItem_ID,
                //Weight  = Weight,
                SideID = SideID,
                DtStart = Convert.ToDateTime(dtStart),
                DtFinish = Convert.ToDateTime(dtEnd)
            };
        
        SetSurface_QNumber(ref i);      
        
        if (SideSurfCount > i.SurfaceNumber)
            res.SurfNumber = 0;
        else
            res.SurfNumber = i.SurfaceNumber - SideSurfCount;


        res.DaysCount = Ecopsy.Tools.DateTimeTools.GetDayDiff(_dtEnd, _dtStart).ToString ();
        res.Summa = (Convert .ToInt16 ( res.DaysCount)  * ContractPrice).ToString () ;
        return res;
    }


    [WebMethod]
    public CallBackValue_SetSurface Check_Surface_Q(string ContractID, string dtStart, string dtEnd, 
                                        string ContractSurfaceItem_ID, bool qPrioritetLevel, int SideSurfCount,
                                        int ContractPrice, string DayCount_ID, string Summa_ID)
     {
         //// если dtStart> dtEnd - считаем что идет редактирование не проверяем очередь  
         //DateTime _dtStart = Convert.ToDateTime(dtStart);
         //DateTime _dtEnd = Convert.ToDateTime(dtEnd);
         //CallBackValue_SetSurface res = new CallBackValue_SetSurface() { SurfNumber = -1, DaysCount_ID = DayCount_ID, Summa_ID = Summa_ID };
         //if (_dtStart > _dtEnd)
         //    return res;


         //wsContract ws = (wsContract)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Contract]; 
         //ContractEntity  c = ws.GetContract(ContractID);
         ////ContractSurfaceItem i = (ContractSurfaceItem)c.ContractSurfaceItemList[ContractSurfaceItem_ID];         
         ////i.DtStart = _dtStart;
         ////i.DtFinish = _dtEnd;
         ////i.BusinesRulesEngine.OwnerAfterChange(Contract_BusinesRulesEngine.CalculateContractSurfaceItemList);    
         
         //SetSurface_QNumber(ref i);

         //if (SideSurfCount > i.SurfaceNumber)
         //    res.SurfNumber = 0;
         //else
         //    res.SurfNumber = i.SurfaceNumber - (SideSurfCount-1);


         //res.DaysCount = Ecopsy.Tools.DateTimeTools.GetDayDiff(_dtEnd, _dtStart).ToString();
         //res.Summa = (Convert.ToInt16(res.DaysCount) * ContractPrice).ToString();
         //return res;

         return null;
        
        
    }


    /// <summary>
    /// Устанавливает номер в очереди для заданной поверхности на заданном диапазоне 
    /// Возвращает 
    /// </summary>
    [WebMethod]
    public void SetSurface_QNumber(ref ContractSurfaceItem SurfItem)
    {
    //    string id = SurfItem.ID;
    //    SecuretyContext sc = AppContext.GetSC();
    //    string s = sc.ConnectionString;
    //    ContractSurface_DistrubeItemList List = new ContractSurface_DistrubeItemList();
    //    List.DtStart = Convert.ToDateTime(SurfItem.DtStart);
    //    List.DtEnd = Convert.ToDateTime(SurfItem.DtFinish);
    //    List.SideID = SurfItem.SideID ;        

    //    List.i_ContractSurfaceItem = SurfItem;

    //    List.Load();


    //    ContractSurfaceItem i = (ContractSurfaceItem)List[SurfItem.ID ];
    //    SurfItem.SurfaceNumber = i.SurfaceNumber;
    }

    public class CallBackValue_SetSurface
    {
        public int SurfNumber { get; set; }
        public string Summa { get; set; }
        public string DaysCount { get; set; }
        public string DaysCount_ID { get; set; }
        public string Summa_ID { get; set; }
    }

    
    [WebMethod]
    public string  TestString()
    {      
        return "Привет";
    }

    [WebMethod]
    public CallBackContextMenu CallContextMenu(string ConextMenuType, int X, int Y, string Params)
    {
        string HtmlResult= string.Empty ;
        // если 
        if (GlobalConstants.ConextMenuType.mTreeDictionary.ToString().IndexOf (ConextMenuType)>-1)
        {
            return new CallBackContextMenu() { HTML = TreePostbackControl.GetContextMenu(Params), X = X, Y = Y}; 
        }
        return null;
        
    }

    public class CallBackContextMenu
    {
        public string HTML { get; set; }
        public int X{ get; set; }
        public int Y{ get; set; }        
    }

    [WebMethod]
    public CallBackValue_SetEditingPeriod SetEditingPeriod(int PeriodType, string dtStart, string dtEnd)
    {
        DateTime _DtStart;
        DateTime _DtEnd;
        try {
            _DtStart =Convert .ToDateTime (dtStart );
            _DtEnd =Convert .ToDateTime (dtEnd );
        }
        catch 
        {

            return new CallBackValue_SetEditingPeriod() { dtStart = dtStart, dtEnd = dtEnd };
        }

        switch (PeriodType)
        {
            case 1: // день
                {
                    if (Ecopsy.Tools.DateTimeTools.GetDayDiff(_DtEnd, _DtStart) > 31)
                        return new CallBackValue_SetEditingPeriod() { dtStart = _DtStart.ToShortDateString(), dtEnd = _DtStart.AddMonths(1).ToShortDateString() };

                    return new CallBackValue_SetEditingPeriod() { dtStart = dtStart, dtEnd = dtEnd };
                }
            case 2:// неделя
                {
                    _DtStart = Ecopsy.Tools.DateTimeTools.GetFisrtDayInWeek (_DtStart);
                    _DtEnd = Ecopsy.Tools.DateTimeTools.GetLastDayInWeek(_DtEnd);
                    if (Ecopsy.Tools.DateTimeTools.GetDiff(_DtStart, _DtEnd, Ecopsy.Tools.DateTimeTools.TimePeriod.Month) > 16)
                    {
                        _DtEnd = _DtStart.AddDays(7 * 16);
                    }

                    if (Ecopsy.Tools.DateTimeTools.GetDiff(_DtStart, _DtEnd, Ecopsy.Tools.DateTimeTools.TimePeriod.Month) <1)
                    {
                        _DtEnd = _DtStart.AddDays(7);
                    }


                    return new CallBackValue_SetEditingPeriod() { dtStart = _DtStart.ToShortDateString(), dtEnd = _DtEnd.ToShortDateString() };
                }
                

            case 3:// месяц
                {
                    _DtStart = Ecopsy.Tools.DateTimeTools.GetFisrtDayInMonth(_DtStart);
                    _DtEnd = Ecopsy.Tools.DateTimeTools.GetLastDayInMonth (_DtEnd);
                    return new CallBackValue_SetEditingPeriod() { dtStart = _DtStart.ToShortDateString(), dtEnd = _DtEnd.ToShortDateString() };
                }
            default:
                return new CallBackValue_SetEditingPeriod() { dtStart = dtStart, dtEnd = dtEnd };
        }
    }

    public class CallBackValue_SetEditingPeriod
    {
        public string dtStart { get; set; }
        public string dtEnd { get; set; }
    }

    



}

